<script setup>
import MyTable from '@/components/MyTable.vue';
import StickPopup from '@/components/StickPopup.vue';
import { ref, onMounted } from 'vue';
import { Search, Filter, ArrowDown, QuestionFilled } from '@element-plus/icons-vue'

// 客户列表列数据
const columns = [
    { title: '客户简称', key: 'customerShortName', sortable: true },
    { title: '应收合计', key: 'receivableTotal', sortable: true },
    { title: '合同应收金额', key: 'contractReceivable', sortable: true },
    { title: '合同欠费月数', key: 'overdueMonths', sortable: true },
    { title: '合同已收费至', key: 'chargedUpTo', sortable: true },
    { title: '合同到期时间', key: 'expireTime', sortable: true },
    { title: '订单及其他应收', key: 'orderOtherReceivable', sortable: true },
    { title: '最近一次收费时间', key: 'lastChargeTime', sortable: true },
    { title: '增值税类型', key: 'vatType', sortable: true },
    { title: '客户经理', key: 'operation', sortable: true }
];

const mockData = ref([]);
const loading = ref(true);
const activeName = ref('all'); // 默认选中"全部客户"
const totalReceivable = ref('0.00'); // 应收合计
const contractReceivable = ref('0.00'); // 合同应收金额
const orderOtherReceivable = ref('0.00'); // 订单及其他应收

// 筛选表单数据
const filterForm = ref({
    serviceAdvisor: '',
    searchAdvisor: '',
    serviceType: '',
    expireTimeRange: [],
    chargedUpToRange: [],
    chargeCycle: '',
    customerLevel: '',
    department: '',
    includeSubDept: false,
    region: '',
    vatType: '',
    contactPerson: '',
    lastPayTimeRange: []
});

// 搜索关键词
const searchKeyword = ref('');
// 包含流失
const includeLost = ref(true);

// 处理标签页切换
const handleTabChange = (tabKey) => {
    loading.value = true;
    activeName.value = tabKey;

    setTimeout(() => {
        // 按标签页加载对应数据
        switch (tabKey) {
            case 'all':
                mockData.value = [
                    {
                        customerShortName: '阿里科技',
                        receivableTotal: 0,
                        contractReceivable: 0,
                        overdueMonths: 0,
                        chargedUpTo: '2023-12',
                        expireTime: '2024-12-31',
                        orderOtherReceivable: 0,
                        lastChargeTime: '2023-11-05',
                        vatType: '一般纳税人'
                    },
                    {
                        customerShortName: '腾讯科技',
                        receivableTotal: 0,
                        contractReceivable: 0,
                        overdueMonths: 0,
                        chargedUpTo: '2023-12',
                        expireTime: '2024-06-30',
                        orderOtherReceivable: 0,
                        lastChargeTime: '2023-10-20',
                        vatType: '小规模纳税人'
                    }
                ];
                break;
            case 'receivable':
                mockData.value = [
                    {
                        customerShortName: '百度网络',
                        receivableTotal: 15000,
                        contractReceivable: 15000,
                        overdueMonths: 2,
                        chargedUpTo: '2023-10',
                        expireTime: '2024-09-30',
                        orderOtherReceivable: 0,
                        lastChargeTime: '2023-10-01',
                        vatType: '一般纳税人'
                    }
                ];
                break;
            case 'overdue':
                mockData.value = [
                    {
                        customerShortName: '字节跳动',
                        receivableTotal: 30000,
                        contractReceivable: 30000,
                        overdueMonths: 3,
                        chargedUpTo: '2023-09',
                        expireTime: '2024-08-15',
                        orderOtherReceivable: 0,
                        lastChargeTime: '2023-09-10',
                        vatType: '一般纳税人'
                    }
                ];
                break;
        }

        // 计算金额合计
        calculateTotalAmount();
        loading.value = false;
    }, 500);
};

// 计算金额合计
const calculateTotalAmount = () => {
    const total = mockData.value.reduce((sum, item) => sum + item.receivableTotal, 0);
    const contractTotal = mockData.value.reduce((sum, item) => sum + item.contractReceivable, 0);
    const orderTotal = mockData.value.reduce((sum, item) => sum + item.orderOtherReceivable, 0);

    totalReceivable.value = total.toFixed(2);
    contractReceivable.value = contractTotal.toFixed(2);
    orderOtherReceivable.value = orderTotal.toFixed(2);
};

// 筛选表单提交
const handleFilterSubmit = () => {
    loading.value = true;
    setTimeout(() => {
        // 这里添加实际筛选逻辑
        const filtered = [...mockData.value].filter(item => {
            // 增值税类型筛选
            if (filterForm.value.vatType && item.vatType !== filterForm.value.vatType) return false;
            return true;
        });

        mockData.value = filtered;
        calculateTotalAmount();
        loading.value = false;
    }, 500);
};

// 重置筛选表单
const resetFilterForm = () => {
    filterForm.value = {
        serviceAdvisor: '',
        searchAdvisor: '',
        serviceType: '',
        expireTimeRange: [],
        chargedUpToRange: [],
        chargeCycle: '',
        customerLevel: '',
        department: '',
        includeSubDept: false,
        region: '',
        vatType: '',
        contactPerson: '',
        lastPayTimeRange: []
    };
    // 重新加载当前标签页数据
    handleTabChange(activeName.value);
};

// 搜索功能
const handleSearch = () => {
    if (!searchKeyword.value) {
        // 搜索为空时重新加载当前标签页数据
        handleTabChange(activeName.value);
        return;
    }

    loading.value = true;
    setTimeout(() => {
        const keyword = searchKeyword.value.toLowerCase();
        const filtered = mockData.value.filter(item => {
            return item.customerShortName.toLowerCase().includes(keyword);
        });
        mockData.value = filtered;
        calculateTotalAmount();
        loading.value = false;
    }, 500);
};

// 页面挂载时加载初始数据
onMounted(() => {
    handleTabChange('all');
});
</script>

<template>
    <div class="customer-management">
        <!-- 顶部筛选区域 -->
        <div class="top-filter">
            <div class="top-filter-left">
                <!-- 筛选弹窗 -->
                <stick-popup>
                    <template #show>
                        <div class="filter-btn">
                            <div class="filter-btn-label">筛选</div>
                            <div class="filter-btn-icon">
                                <Filter />
                            </div>
                        </div>
                    </template>
                    <template #content>
                        <div class="filter-form-container">
                            <el-form :model="filterForm" label-width="100px">
                                <!-- 服务顾问 -->
                                <el-form-item label="服务顾问">
                                    <el-select v-model="filterForm.serviceAdvisor" placeholder="请选择">
                                        <!-- 实际项目中添加选项 -->
                                    </el-select>
                                </el-form-item>

                                <el-form-item>
                                    <el-input v-model="filterForm.searchAdvisor" placeholder="搜索服务顾问" />
                                </el-form-item>

                                <!-- 客户服务类型 -->
                                <el-form-item label="客户服务类型">
                                    <el-input v-model="filterForm.serviceType" placeholder="搜索客户服务类型" />
                                </el-form-item>

                                <!-- 到期时间 -->
                                <el-form-item label="到期时间">
                                    <el-date-picker v-model="filterForm.expireTimeRange" type="daterange"
                                        range-separator="到" start-placeholder="请选择日期" end-placeholder="请选择日期" />
                                    <div class="date-options">
                                        <el-button type="text" size="small">3个月内到期</el-button>
                                        <el-button type="text" size="small">2个月内到期</el-button>
                                        <el-button type="text" size="small">本月到期</el-button>
                                        <el-button type="text" size="small">已到期</el-button>
                                    </div>
                                </el-form-item>

                                <!-- 已收费至 -->
                                <el-form-item label="已收费至">
                                    <el-date-picker v-model="filterForm.chargedUpToRange" type="monthrange"
                                        range-separator="到" start-placeholder="请选择月份" end-placeholder="请选择月份" />
                                </el-form-item>

                                <!-- 收费周期 -->
                                <el-form-item label="收费周期">
                                    <div class="cycle-options">
                                        <el-button type="text" size="small" v-model="filterForm.chargeCycle"
                                            @click="filterForm.chargeCycle = 'monthly'">每月收</el-button>
                                        <el-button type="text" size="small" v-model="filterForm.chargeCycle"
                                            @click="filterForm.chargeCycle = 'quarterly'">三个月收</el-button>
                                        <el-button type="text" size="small" v-model="filterForm.chargeCycle"
                                            @click="filterForm.chargeCycle = 'semiannually'">半年收</el-button>
                                        <el-button type="text" size="small" v-model="filterForm.chargeCycle"
                                            @click="filterForm.chargeCycle = 'annually'">一年收</el-button>
                                        <el-button type="text" size="small" v-model="filterForm.chargeCycle"
                                            @click="filterForm.chargeCycle = 'once'">一次性收</el-button>
                                    </div>
                                </el-form-item>

                                <!-- 客户等级 -->
                                <el-form-item label="客户等级">
                                    <el-input v-model="filterForm.customerLevel" placeholder="搜索客户等级" />
                                </el-form-item>

                                <!-- 所属部门 -->
                                <el-form-item label="所属部门">
                                    <el-input v-model="filterForm.department" placeholder="搜索所属部门" />
                                </el-form-item>

                                <!-- 部门包含下级 -->
                                <el-form-item>
                                    <el-checkbox v-model="filterForm.includeSubDept" label="部门包含下级" />
                                </el-form-item>

                                <!-- 片区 -->
                                <el-form-item label="片区">
                                    <el-input v-model="filterForm.region" placeholder="搜索片区" />
                                </el-form-item>

                                <!-- 增值税类型 -->
                                <el-form-item label="增值税类型">
                                    <div class="vat-options">
                                        <el-radio v-model="filterForm.vatType" label="一般纳税人">一般纳税人</el-radio>
                                        <el-radio v-model="filterForm.vatType" label="小规模纳税人">小规模纳税人</el-radio>
                                    </div>
                                </el-form-item>

                                <!-- 联系人 -->
                                <el-form-item label="联系人">
                                    <el-input v-model="filterForm.contactPerson" placeholder="搜索联系人" />
                                </el-form-item>

                                <!-- 最近支付时间 -->
                                <el-form-item label="最近支付时间">
                                    <el-date-picker v-model="filterForm.lastPayTimeRange" type="daterange"
                                        range-separator="到" start-placeholder="请选择日期" end-placeholder="请选择日期" />
                                </el-form-item>
                            </el-form>
                        </div>
                    </template>
                    <template #footer>
                        <div class="filter-actions">
                            <el-button type="text" @click="resetFilterForm">重置</el-button>
                            <el-button type="primary" @click="handleFilterSubmit">确认</el-button>
                        </div>
                    </template>
                </stick-popup>

                <!-- 搜索框 -->
                <div class="search-box">
                    <el-input v-model="searchKeyword" placeholder="请输入客户简称或编号" @keyup.enter="handleSearch">
                        <template #append>
                            <el-button :icon="Search" @click="handleSearch" />
                        </template>
                    </el-input>
                </div>

                <!-- 包含流失 -->
                <el-checkbox v-model="includeLost" label="包含流失" class="include-lost" />
            </div>

            <!-- 右侧操作按钮 -->
            <div class="top-filter-right">
                <el-button type="primary" class="bill-notify">账单通知</el-button>
                <el-button type="primary" class="export-btn">导出</el-button>
            </div>
        </div>

        <!-- 表格区域 -->
        <div class="table-container">
            <!-- 状态标签页 -->
            <div class="status-tabs">
                <el-tabs v-model="activeName" @tab-click="(tab) => handleTabChange(tab.name)" stretch>
                    <el-tab-pane label="全部客户" name="all"></el-tab-pane>
                    <el-tab-pane label="待收客户" name="dai"></el-tab-pane>
                    <el-tab-pane label="合同欠费客户" name="htqf"></el-tab-pane>
                </el-tabs>

                <!-- 金额统计 -->
                <div class="amount-stats">
                    <span>应收合计：{{ totalReceivable }}</span>
                    <span>合同应收金额：{{ contractReceivable }}</span>
                    <span>订单及其他应收：{{ orderOtherReceivable }}</span>
                </div>
            </div>

            <!-- 客户表格 -->
            <div class="customer-table">
                <my-table :loading="loading" :columns="columns" :dataSource="mockData" :showIndex="false"
                    :show-selection="true">
                    <!-- 金额格式化 -->
                    <template #data-receivableTotal="scope">
                        {{ scope.data.receivableTotal.toFixed(2) }}
                    </template>
                    <template #data-contractReceivable="scope">
                        {{ scope.data.contractReceivable.toFixed(2) }}
                    </template>
                    <template #data-orderOtherReceivable="scope">
                        {{ scope.data.orderOtherReceivable.toFixed(2) }}
                    </template>

                    <!-- 操作列 -->
                    <template #data-operation="scope">
                        <el-button type="text" size="small" icon="Edit">编辑</el-button>
                    </template>
                </my-table>
            </div>
        </div>
    </div>
</template>

<style lang="less" scoped>
.customer-management {
    width: 100%;
    min-height: 100vh;
    background-color: #f5f7fa;
    padding-bottom: 20px;
}

.top-filter {
    width: 100%;
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-color: #fff;
    padding: 0 20px;
    box-sizing: border-box;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
    position: sticky;
    top: 0;
    z-index: 10;

    .top-filter-left {
        display: flex;
        align-items: center;
        gap: 15px;

        .filter-btn {
            display: flex;
            align-items: center;
            gap: 5px;
            padding: 0 15px;
            height: 32px;
            border: 1px solid #dcdfe6;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.2s;

            &:hover {
                border-color: #409eff;
                color: #409eff;
            }
        }

        .search-box {
            width: 300px;
        }

        .include-lost {
            margin-left: 10px;
        }
    }

    .top-filter-right {
        display: flex;
        gap: 10px;

        .bill-notify {
            background-color: #ff7d00;
            border-color: #ff7d00;

            &:hover {
                background-color: #ff902b;
                border-color: #ff902b;
            }
        }

        .export-btn {
            background-color: #ffffff;
            color: #ff7d00;
            border-color: #ff7d00;

            &:hover {
                background-color: #fff3e6;
            }
        }
    }
}

.table-container {
    width: calc(100% - 40px);
    margin: 20px auto;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
    padding: 16px;
    box-sizing: border-box;

    .status-tabs {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;
        flex-wrap: wrap;
        gap: 10px;

        .el-tabs__item {
            position: relative;

            .question-icon {
                margin-left: 5px;
                color: #909399;
            }
        }

        .amount-stats {
            display: flex;
            gap: 15px;
            color: #606266;
            font-size: 14px;

            span {
                &:not(:last-child)::after {
                    content: "，";
                }
            }
        }
    }

    .customer-table {
        width: 100%;
        overflow-x: auto;
    }
}

.filter-form-container {
    padding: 15px;
    width: 500px;

    .el-form-item {
        margin-bottom: 15px;
    }

    .date-options,
    .cycle-options {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
        margin-top: 10px;
    }

    .vat-options {
        display: flex;
        gap: 20px;
    }
}

.filter-actions {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    padding: 10px 15px;
    border-top: 1px solid #f0f0f0;
}
</style>